package com.sfzd5.mistakesbook;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.sfzd5.mistakesbook.db.DBHelper;
import com.sfzd5.mistakesbook.db.Exam;
import com.sfzd5.mistakesbook.db.Knowledge;
import com.sfzd5.mistakesbook.db.Mistakes;
import com.sfzd5.mistakesbook.db.MistakesKnowledge;
import com.sfzd5.mistakesbook.db.MistakesStudent;
import com.sfzd5.mistakesbook.db.Student;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class AddMistakesActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    //参数是一个Mistakes对象，根据id是否为-1来确定是更新或添加

    private File cameraSavePath;//拍照照片路径
    private File desPicPath;//拍照照片路径
    private Uri uri;

    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private String photoName = System.currentTimeMillis() + ".jpg";
    private static final int CameraRequestCode = 1;
    private static final int CropRequestCode = 2;

    private Bitmap bitmap;

    private Button bt_create;
    private Button bt_cancel;
    private Spinner sp_exam;
    private ImageButton bt_add_exam;
    private SelectRecyclerView srcv_student;
    private ImageButton bt_open_camera;
    private ImageView iv_img;
    private SelectRecyclerView srcv_knowledge;

    MistakesApplication app;
    InputTextDialog inputTextDialog;

    ArrayAdapter<Exam> examArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_mistakes);

        app = (MistakesApplication) getApplication();

        bt_create = findViewById(R.id.bt_create);
        bt_cancel = findViewById(R.id.bt_cancel);
        sp_exam = findViewById(R.id.sp_exam);
        bt_add_exam = findViewById(R.id.bt_add_exam);
        srcv_student = findViewById(R.id.srcv_student);
        bt_open_camera = findViewById(R.id.bt_open_camera);
        iv_img = findViewById(R.id.iv_img);
        srcv_knowledge = findViewById(R.id.srcv_knowledge);

        inputTextDialog = new InputTextDialog(this);

        bt_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //数据保存到app.curEditMistakes
                if(
                        sp_exam.getSelectedItemId()>=0
                        && srcv_student.getSelected().size()>0
                        && srcv_knowledge.getSelected().size()>0
                        && (bitmap!=null || app.curEditMistakes.id>0)
                ){
                    Exam exam = (Exam) sp_exam.getSelectedItem();
                    ArrayList<Student> selectedStudents = new ArrayList<>();
                    for(Object obj : srcv_student.getSelected()){
                        selectedStudents.add((Student) obj);
                    }
                    ArrayList<Knowledge> selectedKnowledges = new ArrayList<>();
                    for(Object obj : srcv_knowledge.getSelected()){
                        selectedKnowledges.add((Knowledge) obj);
                    }

                    DBHelper helper = DBHelper.getInstance(AddMistakesActivity.this);

                    if(exam.id<0){
                        try {
                            helper.getExamDao().create(exam);
                            app.examList.add(0, exam);
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                    }
                    app.curEditMistakes.exam = exam.exam;

                    if(bitmap!=null) app.curEditMistakes.question = ImageUtils.bitmap2Base64(bitmap);

                    try {
                        //保存所有信息
                        if(app.curEditMistakes.id>0){
                            helper.getMistakesDao().update(app.curEditMistakes);
                        } else {
                            helper.getMistakesDao().create(app.curEditMistakes);
                        }
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }

                    try {
                        Dao<MistakesStudent, Integer> mistakesStudentIntegerDao = helper.getMistakesStudentDao();
                        DeleteBuilder<MistakesStudent, Integer> mistakesStudentIntegerDeleteBuilder = mistakesStudentIntegerDao.deleteBuilder();
                        mistakesStudentIntegerDeleteBuilder.where().eq(MistakesStudent.MISTAKES_ID_FIELD_NAME, app.curEditMistakes.id);
                        mistakesStudentIntegerDeleteBuilder.delete();
                        for(Student student : selectedStudents){
                            if(student.id<0){
                                helper.getStudentDao().create(student);
                                //app.studentList.add(0, student);
                            }
                            MistakesStudent mistakesStudent = new MistakesStudent();
                            mistakesStudent.mistakes = app.curEditMistakes;
                            mistakesStudent.student = student;
                            mistakesStudentIntegerDao.create(mistakesStudent);
                        }

                        Dao<MistakesKnowledge, Integer> mistakesKnowledgeIntegerDao = helper.getMistakesKnowledgeDao();
                        DeleteBuilder<MistakesKnowledge, Integer> mistakesKnowledgeIntegerDeleteBuilder = mistakesKnowledgeIntegerDao.deleteBuilder();
                        mistakesKnowledgeIntegerDeleteBuilder.where().eq(MistakesStudent.MISTAKES_ID_FIELD_NAME, app.curEditMistakes.id);
                        mistakesKnowledgeIntegerDeleteBuilder.delete();
                        for(Knowledge knowledge : selectedKnowledges){
                            if(knowledge.id<0){
                                helper.getKnowledgeDao().create(knowledge);
                                //app.knowledgeList.add(0, knowledge);
                            }
                            MistakesKnowledge mistakesKnowledge = new MistakesKnowledge();
                            mistakesKnowledge.mistakes = app.curEditMistakes;
                            mistakesKnowledge.knowledge = knowledge;
                            mistakesKnowledgeIntegerDao.create(mistakesKnowledge);
                        }
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }

                    setResult(RESULT_OK, null);
                    finish();
                } else {
                    Toast.makeText(AddMistakesActivity.this, "所有信息都要填", Toast.LENGTH_LONG).show();
                }
            }
        });

        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        bt_add_exam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputTextDialog.showInputDialog("请输入名称", new InputTextDialogResultInterface() {
                    @Override
                    public void result(String result) {
                        Exam exam = new Exam();
                        exam.id = -1;
                        exam.exam = result;
                        examArrayAdapter.insert(exam, 0);
                        sp_exam.setSelection(0);
                    }
                });
            }
        });

        bt_open_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goCamera();
            }
        });

        iv_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goCamera();
            }
        });

        examArrayAdapter = new ArrayAdapter<Exam>(this, android.R.layout.simple_spinner_item,app.examList);
        examArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_exam.setPrompt("请选择行星");
        sp_exam.setAdapter(examArrayAdapter);
        sp_exam.setSelection(0);

        ArrayList<Object> selectStudents = null;
        ArrayList<Object> selectKnowledges = null;

        if(app.curEditMistakes.id>0){
            //是编辑
            try {
                selectStudents = takeStudents(app.curEditMistakes);
                selectKnowledges = takeKnowledges(app.curEditMistakes);
                Bitmap initbitmap = ImageUtils.base642Bitmap(app.curEditMistakes.question);
                Glide.with(this).load(initbitmap).into(iv_img);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else {
            selectStudents = new ArrayList<>();
            selectKnowledges = new ArrayList<>();
        }

        srcv_student.setSingleSelect(false);
        srcv_student.setVal(
                "学生",
                app.studentList,
                selectStudents,
                new AddNewItemInterface() {
                    @Override
                    public void addNewItem() {
                        //插入
                        inputTextDialog.showInputDialog("输入学生姓名", new InputTextDialogResultInterface() {
                            @Override
                            public void result(String result) {
                                Student student = new Student();
                                student.name = result;
                                student.grade = app.readGrade();
                                srcv_student.addNewObject(student);
                            }
                        });
                    }
                });

        srcv_knowledge.setSingleSelect(false);
        srcv_knowledge.setVal(
                "知识点",
                app.knowledgeList,
                selectKnowledges,
                new AddNewItemInterface() {
                    @Override
                    public void addNewItem() {
                        //插入
                        inputTextDialog.showInputDialog("输入知识点", new InputTextDialogResultInterface() {
                            @Override
                            public void result(String result) {
                                Knowledge knowledge = new Knowledge();
                                knowledge.knowledge = result;
                                srcv_knowledge.addNewObject(knowledge);
                            }
                        });
                    }
                });

        if (!EasyPermissions.hasPermissions(this, permissions)) {
            //没有打开相关权限、申请权限
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
        } else {

            //externalcache
            File dir = new File(getExternalCacheDir(), "mbtmp");
            if (!dir.exists())
                dir.mkdirs();
            cameraSavePath = new File(dir, photoName);
            desPicPath = new File(dir, "des_" + photoName);

            File tf = new File(dir, "t.txt");
            FileOutputStream outputStream;
            try {
                outputStream = new FileOutputStream(tf, true);
                outputStream.write("msg".getBytes());
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //框架要求必须这么写
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //成功打开权限
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    //获取权限失败
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Toast.makeText(this, "相机权限获取失败，请自己设置", Toast.LENGTH_SHORT).show();
    }

    private void photoClip(Uri uri) {
        //初始化UCrop配置
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //是否能调整裁剪框
        options.setFreeStyleCropEnabled(true);
        //desUri = FileProvider.getUriForFile(this, "com.sfzd5.mistakesbook.fileprovider", desPicPath);
        UCrop.of(Uri.fromFile(cameraSavePath), Uri.fromFile(desPicPath))
                .withAspectRatio(16, 9)
                .withOptions(options)
                .withMaxResultSize(800, 800)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String photoPath;
        //
        if (requestCode == CameraRequestCode && resultCode == RESULT_OK) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                photoPath = cameraSavePath.getAbsolutePath();
                //photoClip(Uri.fromFile(cameraSavePath));
                photoClip(uri);
                //uri = FileProvider.getUriForFile(this, "com.sfzd5.mistakesbook.fileprovider", cameraSavePath);
                //photoClip(uri);
            } else {
                photoPath = uri.getEncodedPath();
                photoClip(uri);
            }
            Log.d("拍照返回图片路径:", photoPath);
            //Glide.with(this).load(photoPath).into(iv_img);
/*        } else if (requestCode == CropRequestCode && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();

            if (bundle != null) {
                //在这里获得了剪裁后的Bitmap对象，可以用于上传
                Bitmap image = bundle.getParcelable("data");
                //设置到ImageView上
                iv_img.setImageBitmap(image);
            }
*/
        } else if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            final Uri resultUri = UCrop.getOutput(data);
            try {
                bitmap = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(resultUri));
                if(bitmap.getWidth()>800){
                    bitmap = ImageUtils.scaleBitmap(bitmap, 800.0f / bitmap.getWidth());
                }
                Glide.with(this).load(bitmap).into(iv_img);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        } else if (resultCode == UCrop.RESULT_ERROR) {
            final Throwable cropError = UCrop.getError(data);
            cropError.printStackTrace();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    //激活相机操作
    private void goCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this, "com.sfzd5.mistakesbook.fileprovider", cameraSavePath);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(cameraSavePath);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        this.startActivityForResult(intent, CameraRequestCode);
    }

    private ArrayList takeStudents(Mistakes mistakes) throws SQLException {
        QueryBuilder<MistakesStudent, Integer> mistakesStudentQueryBuilder = DBHelper.getInstance(this).getMistakesStudentDao().queryBuilder();
        mistakesStudentQueryBuilder.selectColumns(MistakesStudent.STUDENT_ID_FIELD_NAME);
        mistakesStudentQueryBuilder.where().eq(MistakesStudent.MISTAKES_ID_FIELD_NAME, mistakes.id);

        QueryBuilder<Student, Integer> studentIntegerQueryBuilder = DBHelper.getInstance(this).getStudentDao().queryBuilder();
        studentIntegerQueryBuilder.where().in("id", mistakesStudentQueryBuilder);

        return (ArrayList) studentIntegerQueryBuilder.query();
    }

    private ArrayList takeKnowledges(Mistakes mistakes) throws SQLException {
        QueryBuilder<MistakesKnowledge, Integer> mistakesKnowledgeIntegerQueryBuilder = DBHelper.getInstance(this).getMistakesKnowledgeDao().queryBuilder();
        mistakesKnowledgeIntegerQueryBuilder.selectColumns(MistakesKnowledge.KNOWLEDGE_ID_FIELD_NAME);
        mistakesKnowledgeIntegerQueryBuilder.where().eq(MistakesKnowledge.MISTAKES_ID_FIELD_NAME, mistakes.id);

        QueryBuilder<Knowledge, Integer> knowledgeIntegerQueryBuilder = DBHelper.getInstance(this).getKnowledgeDao().queryBuilder();
        knowledgeIntegerQueryBuilder.where().in("id", mistakesKnowledgeIntegerQueryBuilder);

        return (ArrayList) knowledgeIntegerQueryBuilder.query();
    }
}